from flask import jsonify

class StatusCode:
    OPERATION_SUCCESS = {"code": 200, "msg": "Operation successful"}
    INVALID_DATA = {"code": 400, "msg": "Invalid data"}
    NOT_FOUND = {"code": 404, "msg": "Resource not found"}
    INTERNAL_ERROR = {"code": 500, "msg": "Internal server error"}

class JsonResult:
    def __init__(self, code=None, msg=None, data=None, status_obj=None):
        if status_obj:
            self.code = status_obj["code"]
            self.msg = status_obj["msg"]
        else:
            self.code = code
            self.msg = msg

        self.data = data

    def to_dict(self):
        """ 转换为字典格式，便于 jsonify 处理 """
        response = {"code": self.code, "msg": self.msg}
        if self.data is not None:
            response["data"] = self.data
        return response

    @staticmethod
    def ok(data=None):
        """ 成功响应 """
        return JsonResult(status_obj=StatusCode.OPERATION_SUCCESS, data=data)

    @staticmethod
    def error(status_obj, data=None):
        """ 失败响应 """
        return JsonResult(status_obj=status_obj, data=data)

    def to_response(self):
        """ 转换为 Flask 可用的 JSON 响应 """
        return jsonify(self.to_dict()), self.code
